﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.OleDb;

namespace AdminManager.Utility
{
    public class AccessHelper
    {
        public static string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";

        public static DataTable GetDataTable(string sql)
        {
            DataSet ds = GetDataSet(sql);
            if (ds != null)
            {
                return ds.Tables[0];
            }
            return null;
        }

        public static DataSet GetDataSet(string sql)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();

                OleDbDataAdapter myAdpater = new OleDbDataAdapter(sql, conn);

                OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdpater);

                DataSet ds = new DataSet();

                return ds;
            }
        }

        public static OleDbDataReader ExecuteReader(string sql)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                OleDbDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                return dr;
            }
        }

        public static object ExecuteScalar(string sql)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                object obj = cmd.ExecuteScalar();
                return obj;
            }
        }

        public static int ExecuteNonQuery(string sql)
        {
            using (OleDbConnection conn = new OleDbConnection(connectionString))
            {
                if (conn.State != ConnectionState.Open)
                    conn.Open();
                OleDbCommand cmd = new OleDbCommand(sql, conn);
                int ret = cmd.ExecuteNonQuery();
                return ret;
            }
        }

        public static void SetConnectionStringByName(string DataBaseConfigName)
        {
            connectionString = "";
        }
    }
}